import React, { useState, useEffect, useCallback } from 'react';
import { Form, Row, Col, Input, Select, Button, DatePicker, TreeSelect, Spin, message, Radio, Checkbox, Upload, Image } from 'antd';
import { dictData,getAddList, getEditList, getEditInfo, saveAdd, viewAttachment,uploadFile } from '@/services/prefiling/onlineCollecting';
import { useModel,useLocation } from 'umi';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';
import { getTabState, persistTabState ,getActiveTabKey} from '@/utils/tabPersistence';
import DynamicDictSelect from '@/components/OnlineCollecting/DynamicDictSelect';
import DictComboboxSelect from '@/components/OnlineCollecting/DictComboboxSelect';
import dayjs from 'dayjs';

const { TextArea } = Input;

interface QueryField {
  name: string;
  label: string;
  syllableType?: number;
  dictCode?: string;
  options?: Array<{ label: string; value: any }>;
  defaultValue?: string;
  code?: string;
  fieldPrompt?: string;
  isEmpty?: string;
}

interface DictionaryItem {
  value: string;
  label: string;
  id?: number;
  dictId?: number;
  type?: string;
  description?: string;
  [key: string]: any;
}

interface TreeDataItem {
  value: string;
  title: string;
  children?: TreeDataItem[];
}

type FieldOptions = Record<string, DictionaryItem[]>;
type FieldTreeData = Record<string, TreeDataItem[]>;
type FieldLoading = Record<string, boolean>;

const OnlineCollectingAddPage: React.FC = () => {
  const [form] = Form.useForm();
  const [editFields, setEditFields] = useState<QueryField[]>([]);
  const [editFormData, setEditFormData] = useState<Record<string, any>>({}); 
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [sessionType] = useState<Array<{ value: string; label: string }>>([]);
  const [fieldOptions, setFieldOptions] = useState<FieldOptions>({});
  const [fieldLoading, setFieldLoading] = useState<FieldLoading>({});
  const [fieldTreeData, setFieldTreeData] = useState<FieldTreeData>({});
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [previewImage, setPreviewImage] = useState('');
  const [uploading, setUploading] = useState(false);
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const location = useLocation();

  const tabKey = getActiveTabKey();
  const state = location.state || (tabKey ? getTabState(tabKey) : null);
  const { typeCode, fileState, arrangeDimension, fullId, pageLink, modelType,fullNo,id,queryType } =state;

  useEffect(() => {
    if (tabKey && state) {
      persistTabState(tabKey, state);
    }
  }, [tabKey, state]);

  // 初始化加载数据
  useEffect(() => {
    const fetchInitialData = async () => {
      try {
        setLoading(true);
        await fetchQueryDynamicData();
        if (id) {
            await fetchEditInfo();
         }
      } catch (error) {
        message.error('初始化数据失败');
      } finally {
        setLoading(false);
      }
    };

    fetchInitialData();
  }, [typeCode, arrangeDimension, fullId, pageLink,id]);


  // 新增：获取编辑信息
  const fetchEditInfo = async () => {
    try {
      const res = await getEditInfo({ id });
      if (res.code === 0 && res.data) {
        setEditFormData(res.data);
        
        // 处理编辑数据，适配表单
        const processedValues = processEditData(res.data, editFields);
        form.setFieldsValue(processedValues);
        
        // 处理附件字段
        const attachmentField = editFields.find(f => f.syllableType === 9);
        if (attachmentField && res.data[attachmentField.code]) {
          setFileList([{
            uid: res.data[attachmentField.code],
            name: '已上传文件',
            status: 'done',
            url: res.data[attachmentField.code],
          }]);
        }
      } else {
        message.error(res.message || '获取编辑信息失败');
      }
    } catch (error) {
      console.error('获取编辑信息失败:', error);
      message.error('获取编辑信息失败');
    }
  };

  // 新增：处理编辑数据适配表单
  const processEditData = (data: Record<string, any>, fields: QueryField[]): Record<string, any> => {
    const result: Record<string, any> = {};
    
    fields.forEach(field => {
      const value = data[field.code];
      if (value === null || value === undefined) return;
      
      const syllableType = field.syllableType || 1;
      
      switch (syllableType) {
        case 4: // 日期
        case 5: // 时间
        case 6: // 年月
        case 7: // 年
          result[field.name] = value ? dayjs(value) : null;
          break;
        
        case 11: // 多选框
        case 14: // 多选树形选择框
          result[field.name] = typeof value === 'string' ? value.split(',') : value;
          break;
          
        case 12: // 时间段
          if (value && typeof value === 'string' && value.includes('~')) {
            const [start, end] = value.split('~');
            result[`start${field.name}`] = start ? dayjs(start) : null;
            result[`end${field.name}`] = end ? dayjs(end) : null;
          }
          break;
          
        default:
          result[field.name] = value;
      }
    });
    
    return result;
  };

  // 查询条件配置
  const fetchQueryDynamicData = async () => {
    try {
      let res;
      if(id){
        res = await getEditList({
            typeCode,
            templateType: arrangeDimension,
            fullId,
            pageLink,
            queryType
          });
      }else{
        res = await getAddList({
            typeCode: typeCode,
            templateType: arrangeDimension,
            fullId: fullId,
            pageLink: pageLink
          });
      }
      console.log(res)
      if (res.code === 0) {
        const convertedFields = convertToSearchFields(res.data)
        setEditFields(convertedFields);
        await fetchDictionaryData(res.data || []);
      } else {
        message.error(res.message);
      }
    } catch (error) {
      message.error('获取查询字段配置失败');
      console.error('获取查询字段配置失败:', error);
    }
  };


  // 转换动态查询表单数据格式
  const convertToSearchFields = (originalData: any[]): QueryField[] => {
    return originalData.map(item => {
      const field: QueryField = {
        ...item,
        name: item.code,
        label: item.name,
        syllableType: item.syllableType || '1',
        
      };

      if (item.options && item.options.length > 0) {
        field.options = item.options.map(opt => ({
          label: opt.label || opt.value,
          value: opt.value
        }));
      }
      
      return field;
    });
  };

  // 获取字典数据
  const fetchDictionaryData = async (fields: QueryField[]) => {
    const fieldsToLoad = fields.filter(field => {
      const syllableType = field.syllableType || 1;
      return [2, 10, 11].includes(syllableType) && field.dictCode;
    });

    const options: FieldOptions = {};
    const treeData: FieldTreeData = {};
    const loadingStates: FieldLoading = {};

    try {
      // 设置所有字段的加载状态
      fieldsToLoad.forEach(field => {
        loadingStates[field.code] = true;
      });
      setFieldLoading(prev => ({ ...prev, ...loadingStates }));

      // 并行获取所有字典数据
      const results = await Promise.all(
        fieldsToLoad.map(async field => {
          try {
            const res = await dictData({ dictType: field.dictCode! });
            return { field, data: res || [] };
          } catch (error) {
            console.error(`加载字典数据失败 ${field.name}:`, error);
            return { field, data: [] };
          }
        })
      );
    //   console.log(results)
      // 处理获取到的数据
      results.forEach(({ field, data }) => {
        const syllableType = field.syllableType || 1;
        
        if ([2, 3, 10, 11].includes(syllableType)) {
          options[field.code] = data;
        } else if ([13, 14].includes(syllableType)) {
          treeData[field.code] = data;
        }
      });

      // 更新状态
      setFieldOptions(prev => ({ ...prev, ...options }));
      setFieldTreeData(prev => ({ ...prev, ...treeData }));
    } finally {
      // 清除加载状态
      fieldsToLoad.forEach(field => {
        loadingStates[field.code] = false;
      });
      setFieldLoading(prev => ({ ...prev, ...loadingStates }));
    }
  };

  // 处理文件上传
  const handleUpload = async (file: File) => {
    try {
      setUploading(true);
      // 这里替换为您的上传接口
      const res = await uploadFile(fullId,file)

      if (res.code === 0) {
        message.success('上传成功');
        setFileList([{
          uid: res.data.id,
          name: res.data.fileName,
          status: 'done',
          url: res.data.id, // 保存文件ID用于预览
        }]);
        return res.data.id;
      } else {
        message.error(res.msg);
        return null;
      }
    } catch (error) {
      console.error('上传失败:', error);
      message.error('上传失败');
      return null;
    } finally {
      setUploading(false);
    }
  };

  // 预览文件
  const handlePreview = async (id: string) => {
    try {
      const blob = await viewAttachment({
        id,
        fullId
      });
      const url = URL.createObjectURL(blob);
      setPreviewImage(url);
    } catch (error) {
      console.error('预览失败:', error);
      message.error('预览失败');
    }
  };

  // 获取必填校验规则
  const getFieldRules = (field: QueryField) => {
    if (!field.isEmpty) return [];
    
    const isEmpty = field.isEmpty.split("");
    let isRequired;
    
    if (fileState === "00") {
      isRequired = (isEmpty[0] === "1") ? false : true;
    } else {
      isRequired = (isEmpty[1] === "1") ? false : true;
    }
    return isRequired ? [{ required: true, message: `${field.label}不能为空` }] : [];
  };

  const parseDefaultValue = useCallback((defaultValue: string = ''): string => {
    if (!defaultValue) return '';
    
    const defaultData = sessionType.filter(item => item.value === defaultValue);
    if (!defaultData.length) return defaultValue;

    switch (defaultValue) {
      case "NOW_YEAR":
        return getNowDate("year");
      case "NOW_MONTH":
        return getNowDate("month");
      case "NOW_DATE":
        return getNowDate();
      case "NOW_DATETIME":
        return getNowDate("datetime");
      default:
        return currentUser?.[defaultValue] || "";
    }
  }, [sessionType, currentUser]);

  const getNowDate = (type?: string): string => {
    const now = new Date();
    const year = now.getFullYear().toString();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const date = now.getDate().toString().padStart(2, '0');
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    const seconds = now.getSeconds().toString().padStart(2, '0');

    switch (type) {
      case "year":
        return year;
      case "month":
        return `${year}-${month}`;
      case "datetime":
        return `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`;
      default:
        return `${year}-${month}-${date}`;
    }
  };

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      setSubmitting(true);
      const values = await form.validateFields();
      const processedValues = processFormValues(values, editFields);
      const res = await saveAdd({
        ...processedValues,
        typeCode,
        arrangeDimension,
        fullId,
        fileState,
        pageLink,
        fullNo,
      });

      if (res.code === 0) {
        message.success('提交成功');
        // history.goBack();
      } else {
        message.error(res.message);
      }
    } catch (error) {
      console.error('提交失败:', error);
      message.error('提交失败，请检查表单');
    } finally {
      setSubmitting(false);
    }
  };

  // 处理表单值：转换日期格式和空值
  const processFormValues = (values: any, fields: QueryField[]) => {
    const result: any = {};
    
    // 创建字段类型映射，便于快速查找字段类型
    const fieldTypeMap: Record<string, number> = {};
    fields.forEach(field => {
      fieldTypeMap[field.name] = field.syllableType || 1;
    });
    
    // 处理时间段字段
    fields
      .filter(field => field.syllableType === 12)
      .forEach(field => {
        const startField = `start${field.name}`;
        const endField = `end${field.name}`;
        
        // 处理开始时间
        if (values[startField]) {
          result[startField] = dayjs(values[startField]).format('YYYY-MM-DD');
        } else {
          result[startField] = values[startField] || '';
        }
        
        // 处理结束时间
        if (values[endField]) {
          result[endField] = dayjs(values[endField]).format('YYYY-MM-DD');
        } else {
          result[endField] = values[endField] || '';
        }
      });
    
    // 处理其他字段
    Object.keys(values).forEach(key => {
      // 跳过已处理的时间段字段
      if (key.startsWith('start') || key.startsWith('end')) return;
      
      const value = values[key];
      
      // 处理空值
      if (value === undefined || value === null) {
        result[key] = '';
        return;
      }
      
      // 获取字段类型
      const fieldType = fieldTypeMap[key];
      
      // 处理日期/时间字段
      if ([4, 5, 6, 7].includes(fieldType)) {
        if (value) {
          // 根据不同类型格式化日期
          switch (fieldType) {
            case 5: // 时间框
              result[key] = dayjs(value).format('YYYY-MM-DD HH:mm:ss');
              break;
            case 6: // 年月
              result[key] = dayjs(value).format('YYYY-MM');
              break;
            case 7: // 年
              result[key] = dayjs(value).format('YYYY');
              break;
            default: // 默认日期格式
              result[key] = dayjs(value).format('YYYY-MM-DD');
          }
        } else {
          result[key] = value || '';
        }
      } 
      // 处理多选字段（多选框和多选树形选择框）
      else if ([11, 14].includes(fieldType)) {
        if (Array.isArray(value)) {
          result[key] = value.join(',');
        } else {
          result[key] = value || '';
        }
      }
      // 其他字段
      else {
        result[key] = value || '';
      }
    });
    
    return result;
  };

  // 关闭页面
  const handleClose = () => {
    window.closeCurrentTab();
  };

  const renderFormItem = (field: QueryField) => {
    // 优先使用编辑数据中的值
    const editValue = editFormData[field.code];
    const hasEditValue = editValue !== undefined && editValue !== null;
    
    const fieldPrompt = field.fieldPrompt || `请输入${field.label}`;
    const syllableType = field.syllableType || 1;
    const options = fieldOptions[field.name] || [];
    const treeData = fieldTreeData[field.name] || [];
    const itemLoading = fieldLoading[field.name] || false;
  
    if (itemLoading) {
      return <Spin size="small" />;
    }
  
    const commonProps = {
      name: field.name,
      className: `${field.code}`,
      placeholder: fieldPrompt,
      style: { width: '100%' } // 所有控件宽度100%
    };
  
    // 获取字段值：优先使用编辑值，其次使用默认值
    const getDefaultValue = () => {
      if (hasEditValue) {
        return editValue;
      }
      return parseDefaultValue(field.defaultValue);
    };
  
    const datePickerProps = {
      ...commonProps,
      className: `table_input time-input ${field.code}`,
      defaultValue: getDefaultValue()
    };
  
    switch (syllableType) {
      case 1: // 文本框
        return (
          <Input 
            {...commonProps}
            className={`table_input ${field.code}`}
            defaultValue={getDefaultValue()}
          />
        );
       case 2: // 数据字典下拉框 - 确保可以保留输入值
        if (field.code === "nativePlace") {
            return (
            <div style={{ display: 'flex', width: '100%' }}>
                <DictComboboxSelect
                dictCode={field.dictCode!}
                className="dictSelect province"
                style={{ width: '48%' }}
                placeholder={fieldPrompt}
                value={getDefaultValue()}
                onChange={(value) => form.setFieldsValue({ [field.name]: value })}
                />
                <DictComboboxSelect
                dictCode={field.dictCode!} // 如果需要不同的字典，可以修改这里的dictCode
                style={{ width: '48%', marginLeft: '4%' }}
                placeholder={fieldPrompt}
                value={getDefaultValue()}
                onChange={(value) => form.setFieldsValue({ [field.name]: value })}
                />
            </div>
            );
        }
        console.log(getDefaultValue())
        return (
           
            <DictComboboxSelect
            dictCode={field.dictCode!}
            className={`dictSelect ${field.code}`}
            placeholder={fieldPrompt}
            defaultValue={getDefaultValue()}
            onChange={(value) => form.setFieldsValue({ [field.name]: value })}
            />
        );
      case 3: // 接口型下拉框 - 添加按需查询功能
      return (
        <DynamicDictSelect 
        field={field}
        commonProps={commonProps}
        defaultValue={getDefaultValue()}
        className={field.code}
        />)
      case 4: // 日期
        return (
          <DatePicker
            {...datePickerProps}
            format="YYYY-MM-DD"
          />
        );
        
      case 5: // 时间框
        return (
          <DatePicker
            {...datePickerProps}
            showTime
            format="YYYY-MM-DD HH:mm:ss"
          />
        );
        
      case 6: // 年月
        return (
          <DatePicker
            {...datePickerProps}
            picker="month"
            format="YYYY-MM"
          />
        );
        
      case 7: // 年
        return (
          <DatePicker
            {...datePickerProps}
            picker="year"
            format="YYYY"
          />
        );
        
      case 8: // 文本域 - 单独占一行
        return (
          <TextArea
            {...commonProps}
            rows={4}
            className={`table_textarea ${field.code}`}
            defaultValue={getDefaultValue()}
          />
        );
        
      case 9: // 附件框 - 单独占一行
        return (
          <div>
            <Upload
              fileList={fileList}
              beforeUpload={async (file) => {
                const fileId = await handleUpload(file);
                return false; // 阻止默认上传
              }}
              onRemove={() => setFileList([])}
              maxCount={1}
              onPreview={() => handlePreview(fileList[0]?.url as string)}
            >
              <Button icon={<UploadOutlined />} loading={uploading}>
                上传图片
              </Button>
            </Upload>
            {previewImage && (
              <Image
                width={200}
                style={{ display: 'none' }}
                src={previewImage}
                preview={{
                  visible: !!previewImage,
                  src: previewImage,
                  onVisibleChange: (visible) => {
                    if (!visible) setPreviewImage('');
                  },
                }}
              />
            )}
          </div>
        );
      
      case 10: // 单选框
        return (
          <Radio.Group
            {...commonProps}
            defaultValue={getDefaultValue()}
            options={options.map(item => ({
              label: item.label,
              value: item.value
            }))}
          />
        );
        
      case 11: // 多选框 - 根据新数据结构处理
        // 处理编辑数据：如果是字符串，则拆分为数组
        let defaultValue = getDefaultValue();
        if (hasEditValue && typeof defaultValue === 'string') {
          defaultValue = defaultValue.split(',');
        }
        
        return (
          <Checkbox.Group
            {...commonProps}
            defaultValue={defaultValue}
            options={options.map(item => ({
              label: item.label,
              value: item.value
            }))}
          />
        );
        
      case 12: // 时间段
        // 处理编辑数据：如果是字符串，则拆分为开始和结束时间
        let [startDate, endDate] = field.defaultValue ? field.defaultValue.split("~") : ['', ''];
        if (hasEditValue && typeof editValue === 'string') {
          [startDate, endDate] = editValue.split("~");
        }
        
        return (
          <div style={{ display: 'flex', width: '100%' }}>
            <DatePicker
              {...datePickerProps}
              name={`start${field.name}`}
              className={`table_input startTime start${field.code}`}
              defaultValue={startDate ? dayjs(startDate) : undefined}
              style={{ width: '48%' }}
            />
            <span style={{ width: '4%', textAlign: 'center' }}>-</span>
            <DatePicker
              {...datePickerProps}
              name={`end${field.name}`}
              className={`table_input endTime end${field.code}`}
              defaultValue={endDate ? dayjs(endDate) : undefined}
              style={{ width: '48%' }}
            />
          </div>
        );
        
      case 13: // 树形选择框
      case 14: // 多选树形选择框
        let treeDefaultValue = getDefaultValue();
        // 处理编辑数据：如果是字符串，则拆分为数组（多选）或直接使用（单选）
        if (hasEditValue && typeof treeDefaultValue === 'string') {
          if (syllableType === 14) { // 多选树形选择框
            treeDefaultValue = treeDefaultValue.split(',');
          } else { // 单选树形选择框
            const [txt] = treeDefaultValue.split("?");
            treeDefaultValue = txt;
          }
        }
        
        return (
          <TreeSelect
            {...commonProps}
            className={`treeDynamicDictSelect ${field.code}`}
            treeCheckable={syllableType === 14}
            defaultValue={treeDefaultValue}
            treeData={treeData}
            fieldNames={{ label: 'label', value: 'value', children: 'children' }}
          />
        );
        
      default:
        return (
          <Input 
            {...commonProps}
            className={`table_input ${field.code}`}
            defaultValue={getDefaultValue()}
          />
        );
    }
  };

  if (loading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', padding: 40 }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div style={{ 
        padding: 16,
      }}>
      <Form
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
      >
        <Row>
          {editFields.map((field) => {
            // 文本域和附件框单独处理
            if (field.syllableType === 8 || field.syllableType === 9) {
              return (
                <Col span={24} key={field.name}>
                  <Form.Item 
                    name={field.name}
                    label={field.label}
                    // labelCol={{ span: 2 }}
                    labelCol={{ 
                        style: { 
                          width: '8%', 
                          flex: '0 0 8%' 
                        } 
                    }}
                    wrapperCol={{ span: 18 }}
                    rules={getFieldRules(field)}
                  >
                    <div style={{ 
                      width: '77.4%', 
                      maxWidth: '820px'
                    }}>
                      {renderFormItem(field)}
                    </div>
                  </Form.Item>
                </Col>
              );
            }
            
            // 其他字段每行3个
            return (
              <Col span={8} key={field.name}>
                <Form.Item 
                  name={field.name}
                  label={field.label}
                  rules={getFieldRules(field)}
                >
                  {renderFormItem(field)}
                </Form.Item>
              </Col>
            );
          })}
        </Row>
        <Row>
            
        </Row>
      </Form>
      <div style={{ 
        padding: '10px 0',
        textAlign: 'center',
        }}>
        <Button 
          type="primary" 
          onClick={handleSubmit}
          loading={submitting}
          style={{ marginRight: 16 }}
        >
          提交
        </Button>
        <Button onClick={handleClose}>关闭</Button>
      </div>
      
    </div>
  );
};

export default OnlineCollectingAddPage;